# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from datetime import datetime
from dateutil.relativedelta import relativedelta
from borrow_book.forms import ReturnForm
from db.models import db, User, Book, BorrowCard, BorrowBook
from permission_control import permission_required
from const import PERMISSION, BorrowCardApplyStatus
from log import logger
from config import app

return_blueprint = Blueprint('user_return', __name__)


# 还书逻辑
@return_blueprint.route('/user_borrow/post_return', methods=['POST'])
@login_required
@permission_required(PERMISSION.PERM_RETURN.KEY)
def post_return():
    form = ReturnForm()
    borrow_book_id = form.borrow_book_id.data
    borrow_book = BorrowBook.query.filter_by(id=borrow_book_id, is_return=0).first()
    if form.validate_on_submit():
        
        # 校验借阅记录是否存在
        if not borrow_book:
            flash('借阅记录不存在', 'danger')
            return redirect(url_for('user_borrow.borrow_list'))
        
        # 校验用户是否是借阅者
        if borrow_book.user_id != current_user.id:
            flash('借阅者不是当前用户，请重新登录', 'danger')
            return redirect(url_for('user_borrow.borrow_list'))
        
        # 校验借书证是否过期
        if borrow_book.is_overdue:
            flash('借阅已过期，请支付超期费用', 'danger')
            flash('need_payment', 'action')
            return redirect(url_for('user_borrow.borrow_info', book_id=borrow_book.book_id))
        
        borrow_book.is_overdue = 0
        borrow_book.is_return = 1
        book = Book.query.filter_by(id=borrow_book.book_id).first()
        # 书籍库存+1
        book.available_count += 1
        db.session.commit()
        flash('已还书！', 'success')
    return redirect(url_for('user_borrow.borrow_info', book_id=borrow_book.book_id))


# 支付超期费用
@return_blueprint.route('/user_borrow/post_pay', methods=['POST'])
@login_required
@permission_required(PERMISSION.PERM_RETURN.KEY)
def post_pay():
    form = ReturnForm()
    borrow_book_id = form.borrow_book_id.data
    borrow_book = BorrowBook.query.filter_by(id=borrow_book_id, is_return=0).first()
    if form.validate_on_submit():
        # 校验借阅记录是否存在
        if not borrow_book:
            flash('借阅记录不存在', 'danger')
            return redirect(url_for('user_borrow.borrow_list'))
        
        # 校验用户是否是借阅者
        if borrow_book.user_id != current_user.id:
            flash('借阅者不是当前用户，请重新登录', 'danger')
            return redirect(url_for('user_borrow.borrow_list'))
        
        # 校验借阅记录是否是超期记录
        if not borrow_book.is_overdue:
            flash('借阅记录不是超期记录，无需支付超期费用', 'danger')
            return redirect(url_for('user_borrow.borrow_info', book_id=borrow_book.book_id))
        
        # 校验是否已经支付超期费用
        if borrow_book.is_pay_overdue:
            flash('已支付超期费用，无需重复支付', 'danger')
            return redirect(url_for('user_borrow.borrow_info', book_id=borrow_book.book_id))
        
        # 更新超期记录
        borrow_book.is_pay_overdue = 1
        borrow_book.is_overdue = 0
        borrow_book.return_time = datetime.now() + relativedelta(days=1)
        book = Book.query.filter_by(id=borrow_book.book_id).first()
        db.session.commit()
        flash('已支付成功，请在一天内还书，否则将会再次产生超期费用！', 'success')
    return redirect(url_for('user_borrow.borrow_info', book_id=borrow_book.book_id))